package com.foogui.bootrabbitmq.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Component
public class RabbitHelper {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String exchange, String jsonMsg) {
        this.send(exchange, "", jsonMsg);
    }

    public void send(String exchange, String routingKey, String jsonMsg) {
        String messageId = UUID.randomUUID().toString();
        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                .setMessageId(messageId)
                .setContentType(MediaType.APPLICATION_JSON_VALUE)
                .setTimestamp(new Date())
                .build();
        this.send(exchange, routingKey, jsonMsg, messageProperties,null);
    }

    public void send(String exchange, String routingKey, String jsonMsg, MessageProperties messageProperties,String ttlTime) {

        if (Objects.isNull(messageProperties)) {
            throw new IllegalStateException("messageProperties can not be null");
        }
        // 如果未传id就默认uuid
        if (StringUtils.isBlank(messageProperties.getMessageId())) {
            messageProperties.setMessageId(UUID.randomUUID().toString());
        }
        // 将内容和消息元数据构成消息
        Message message = MessageBuilder
                .withBody(jsonMsg.getBytes(StandardCharsets.UTF_8))
                .andProperties(messageProperties)
                .build();
        // 消息关联类，生产者在异步回调中可以获取消息及其他信息
        CorrelationData correlationData = new CorrelationData();

        correlationData.setReturned(new ReturnedMessage(message, 200, "确定生产者已经发出了消息", exchange, routingKey));
        // 将消息的id设置到correlationData，方便在回调中获取消息id
        correlationData.setId(messageProperties.getMessageId());

        rabbitTemplate.convertAndSend(exchange, routingKey, message,msg -> {
            if(StringUtils.isNotBlank(ttlTime)){
                msg.getMessageProperties().setExpiration(ttlTime);
            }
            return msg;
        },correlationData);
    }

}
